import { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  getUserProfile,
  updateUserProfile,
  updateUserPhoto,
} from "@/store/actions/profile";
import type { RootState } from "@/types/store";
import dayjs from "dayjs";
import { logout } from "../../../store/actions/login";
import { LeftOutline } from "antd-mobile-icons";
import {
  Popup,
  Button,
  DatePicker,
  Dialog,
  Image,
  List,
  Toast,
} from "antd-mobile";
import EditInput from "./components/EditInput";
import EditList from "./components/EditList";
import classNames from "classnames"; // 导入 classNames 函数
import { useInitialState } from "@/utils/use-initial-state";
import { ListItem } from "antd-mobile/es/components/list/list-item";
import { Link, useHistory } from "react-router-dom";
import styles from "./personal.module.scss";
import Profile from "../index";
const ProfileEdit = () => {
  const { userProfile } = useInitialState(getUserProfile, "profile");
  const [inputVisible, setInputVisible] = useState(false);
  const dispatch = useDispatch();
  const fileRef = useRef<HTMLInputElement>(null);
  const [showBirthday, setShowBirthday] = useState(false);
  const history = useHistory();
  useEffect(() => {
    dispatch(getUserProfile() as any);
  }, [dispatch]);
  // const tui = () => {
  //   history.push("../../../pages/Profile/index");
  // };
  type InputPopup = {
    type: "" | "name" | "intro";
    value: string;
    visible: boolean;
  };

  type ListPopup = {
    type: "" | "gender" | "photo";
    visible: boolean;
  };
  const [inputPopup, setInputPopup] = useState<InputPopup>({
    type: "",
    value: "",
    visible: false,
  });
  const onUpdateName = async (value: string) => {
    await dispatch(updateUserProfile({ name: value }) as any);
    Toast.show({
      content: "更新成功",
      duration: 1000,
    });
    // 关闭弹出层
    onInputHide();
  };
  const onInputShow = () => {
    setInputPopup({
      type: "name",
      value: name,
      visible: true,
    });
  };
  const onInputHide = () => {
    setInputPopup({
      type: "",
      value: "",
      visible: false,
    });
  };

  const [listPopup, setListPopup] = useState<ListPopup>({
    type: "",
    visible: false,
  });
  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const photoData = new FormData();
    photoData.append("photo", file);
    await dispatch(updateUserPhoto(photoData) as any);
    onGenderHide();
  };

  const onGenderShow = () => {
    setListPopup({
      type: "gender",
      visible: true,
    });
  };
  // 在 EditList 组件中处理选择性别的逻辑
  const onSelectGender = (selectedGender: string) => {
    onUpdateProfile("gender", selectedGender); // 更新用户性别信息
    // onClose(); // 关闭弹窗
  };
  const onGenderHide = () => {
    setListPopup({
      type: "",
      visible: false,
    });
  };
  const onPhotoShow = () => {
    setListPopup({
      type: "photo",
      visible: true,
    });
  };
  const onIntroShow = () => {
    setInputPopup({
      type: "intro",
      value: intro,
      visible: true,
    });
  };
  const { photo, name, intro, gender, birthday } = userProfile;

  // 更新用户昵称
  const onBirthdayShow = () => {
    setShowBirthday(true);
  };
  const onBirthdayHide = () => {
    setShowBirthday(false);
  };
  const onUpdateProfile = async (
    type: "name" | "intro" | "gender" | "photo" | "birthday",
    value: string
  ) => {
    if (type === "photo") {
      fileRef.current?.click();
    } else {
      await dispatch(updateUserProfile({ [type]: value }) as any);
      onInputHide();
      onGenderHide();
    }
  };
  const onUpdateBirthday = (value: Date) => {
    const birthday = dayjs(value).format("YYYY-MM-DD");

    onUpdateProfile("birthday", birthday);
    onBirthdayHide();
  };

  const onLogout = () => {
    const handler = Dialog.show({
      title: "温馨提示",
      content: "亲，你确定退出吗？",
      actions: [
        [
          {
            key: "cancel",
            text: "取消",
            onClick: () => {
              handler.close();
            },
          },
          {
            key: "logout",
            text: "退出",
            onClick: () => {
              dispatch(logout() as any);
              handler.close();
              history.replace("/login");
            },
          },
        ],
      ],
    });
  };
  // JSX 中展示用户信息
  return (
    <div className={styles.root}>
      <Link className={styles.link} to="/home/Profile" style={{color:'#000',display:'flex',alignItems:'center'}}>
        <LeftOutline style={{ height: "50px" }} />
        <div style={{width:'100%',display:'flex',justifyContent:'center'}}>个人信息</div>
      </Link>
      <List>
        <ListItem
          arrow
          extra={
            <Image
              src={photo}
              style={{ borderRadius: 30 }}
              fit="cover"
              width={30}
              height={30}
            />
          }
          onClick={onPhotoShow}
        >
          头像
        </ListItem>
        <ListItem arrow extra={name} onClick={onInputShow}>
          昵称
        </ListItem>

        <ListItem arrow extra={intro} onClick={onIntroShow}>
          简介
        </ListItem>
        <ListItem
          arrow
          extra={Number(gender) === 0 ? "男" : "女"}
          onClick={onGenderShow}
        >
          性别
          <Popup visible={listPopup.visible} onMaskClick={onGenderHide}>
            <EditList
              type={listPopup.type}
              onUpdateProfile={onUpdateProfile}
              onClose={onGenderHide}
              value={""}
            />
          </Popup>
        </ListItem>
        <ListItem arrow extra={birthday} onClick={onBirthdayShow}>
          生日
        </ListItem>
      </List>
      <DatePicker
        visible={showBirthday}
        value={new Date(birthday)}
        onCancel={onBirthdayHide}
        title="选择年月日"
        min={new Date(1900, 0, 1, 0, 0, 0)}
        max={new Date()}
        onConfirm={onUpdateBirthday}
      />
      <Popup visible={inputPopup.visible} position="right">
        <EditInput
          onUpdateName={onUpdateName}
          onUpdateProfile={onUpdateProfile}
          value={inputPopup.value}
          key={inputPopup.type}
          type={inputPopup.type}
          onClose={onInputHide}
        />
      </Popup>
      <div className="wrapper">
        <Button block color="success" size="large" onClick={onLogout}>
          退出登录
        </Button>
        <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
      </div>
    </div>
  );
};

export default ProfileEdit;
